<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入姓名"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="listQuery.search_date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            size="small"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="lends"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        show-summary
        :summary-method="getSummaries"
        @expand-change="expandChange"
      >
        <el-table-column type="expand" label="#" align="center">
          <template slot-scope="scope">
            <el-table
              :data="scope.row.repayments"
              border
              stripe
              highlight-current-row
              size="small"
            >
              <el-table-column
                label="单号"
                prop="order_no"
                align="center"
              ></el-table-column>
              <el-table-column
                label="时间"
                prop="bill_date"
                align="center"
              ></el-table-column>
              <el-table-column
                label="金额(元)"
                prop="money"
                align="center"
                :formatter="dataFormatter"
              ></el-table-column>
              <el-table-column
                label="备注"
                prop="remark"
                align="center"
              ></el-table-column>
              <el-table-column align="center" label="操作" width="100px">
                <template slot-scope="child">
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="handleDeleteRepay(scope.row.repayments, child)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column
          type="index"
          label="#"
          align="center"
          width="80px;"
        ></el-table-column>
        <el-table-column
          v-for="item in tableColumns"
          :key="item.key"
          align="center"
          :label="item.title"
          :prop="item.key"
          :formatter="dataFormatter"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" width="220px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="handleDelete(scope)"
              >删除</el-button
            >
            <el-button
              type="success"
              size="mini"
              @click="handleRepayment(scope)"
              >还款</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getLendList"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="45%">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
        label-position="right"
        size="small"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="单号" prop="order_no" v-if="dialogType === 'edit'">
          <el-input
            type="text"
            v-model="form.order_no"
            placeholder="单号"
            maxlength="24"
            disabled
          />
        </el-form-item>
        <el-form-item label="时间" prop="order_time">
          <el-date-picker
            v-model="form.order_time"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择开单时间"
            clearable
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="姓名" prop="employee">
          <el-select v-model="form.employee" placeholder="姓名" clearable>
            <el-option
              v-for="item in employees"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号" prop="account_type">
          <el-select
            v-model="form.account_type"
            :placeholder="title + '账号'"
            clearable
          >
            <el-option
              v-for="item in banks"
              :label="item.account"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input v-model="form.money" placeholder="金额" clearable>
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="还款额" prop="repayment">
          <el-input
            v-model="form.repayment"
            placeholder="还款金额"
            clearable
            disabled
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="余额">
          <el-input v-model="balance" placeholder="余额" clearable disabled>
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.desc" placeholder="备注" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="HandleSave"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <!-- 对话框表单 -->
    <el-dialog
      :visible.sync="dlgRepayVisible"
      :title="title + '--还款'"
      width="45%"
    >
      <el-form
        :model="repayForm"
        :rules="repayFormRules"
        ref="repayFormRef"
        label-width="80px"
        label-position="right"
        size="small"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="时间" prop="bill_date">
          <el-date-picker
            v-model="repayForm.bill_date"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择开单时间"
            clearable
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="还款金额" prop="money">
          <el-input v-model="repayForm.money" placeholder="还款金额">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="repayForm.desc" placeholder="备注" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="default" size="small" @click="dlgRepayVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="HandleSaveRepay"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getParentsPath } from "@/utils/index";
import { getCurrentDate } from "@/utils/datetime";
import {
  getFundBills,
  addFundBill,
  updateFundBill,
  delFundBill,
  getRepaymentBills,
  addRepaymentBill,
  delRepaymentBill,
} from "@/api/fundbill";
import { getBanks } from "@/api/bank";
import { getEmployeeList } from "@/api/employee";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: undefined,
  order_no: "",
  order_time: getCurrentDate(),
  employee: undefined,
  account_type: null,
  category: 3,
  money: 0,
  repayment: 0,
  desc: "",
  user: undefined,
};

const defaultRepayForm = {
  id: undefined,
  bill: null,
  bill_date: getCurrentDate(),
  money: 0,
  desc: "",
  user: undefined,
};

export default {
  name: "Lend",
  data() {
    const checkMoney = (rule, value, callback) => {
      if (value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (value <= 0) {
          callback(new Error("必须大于零"));
        } else {
          callback();
        }
      }
    };

    return {
      form: Object.assign({}, defaultForm),
      repayForm: Object.assign({}, defaultRepayForm),

      formRules: {
        employee: [{ required: true, message: "请选择员工", trigger: "blur" }],
        order_time: [
          { required: true, message: "请输入时间", trigger: "blur" },
        ],
        account_type: [
          { required: true, message: "请选择账号", trigger: "blur" },
        ],
        money: [{ required: true, validator: checkMoney, trigger: "blur" }],
      },

      repayFormRules: {
        bill_date: [{ required: true, message: "请输入时间", trigger: "blur" }],
        money: [{ required: true, validator: checkMoney, trigger: "blur" }],
      },

      title: "资金借出",
      lends: [],
      employees: [],
      accountList: [],
      banks: [],
      selectedKeys: [],
      curr_row: null,
      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
      },
      dialogVisible: false,
      dlgRepayVisible: false,
      dialogType: "new",
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        category: 3,
        name: undefined,
        search_date: "",
      },

      tableColumns: [
        {
          key: "order_no",
          title: "单号",
        },
        {
          key: "order_time",
          title: "时间",
        },
        {
          key: "employee_name",
          title: "姓名",
        },

        {
          key: "acc_type_name",
          title: "账号",
        },
        {
          key: "money",
          title: "金额(元)",
        },
        {
          key: "repayment",
          title: "还款额(元)",
        },
        {
          key: "balance",
          title: "余额(元)",
        },
        {
          key: "desc",
          title: "备注",
        },
      ],

      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新建${this.title}`
        : `编辑${this.title}`;
    },
    balance() {
      return this.form.money - this.form.repayment;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getLendList();
    this.getEmployeeList();
    this.getBankList();
  },
  methods: {
    getLendList() {
      this.listLoading = true;
      getFundBills(this.listQuery)
        .then((res) => {
          this.total = res.count;
          this.lends = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取数据失败");
          this.listLoading = false;
        });
    },

    getEmployeeList() {
      getEmployeeList().then((res) => {
        this.employees = res;
      });
    },
    getBankList() {
      getBanks().then((res) => {
        this.banks = res;
      });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "合计";
          return;
        }
        if (
          column.property === "money" ||
          column.property === "repayment" ||
          column.property === "balance"
        ) {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
        } else {
          return;
        }
      });
      return sums;
    },
    dataFormatter(row, column, cellValue, index) {
      if (
        column.property == "money" ||
        column.property == "repayment" ||
        column.property == "balance"
      ) {
        return cellValue.toFixed(2);
      } else {
        return cellValue;
      }
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getLendList();
    },
    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.selectedKeys = [];
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delFundBill(row.id);
          this.getLendList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("删除失败!");
        });
    },
    // 保存操作
    async HandleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          if (!this.form.user) {
            this.form.user = this.uid;
          }
          res = await updateFundBill(this.form);
        } else {
          this.form.user = this.uid;
          try {
            res = await addFundBill(this.form);
            
            this.getLendList();
          } catch (err) {
            console.log(err);
            this.$message.error("保存失败!");
          }
        }

        const { order_no, employee_name, money } = res;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>单号: ${order_no}</div>
              <div>姓名: ${employee_name}</div>
              <div>金额: ${money}</div>
            `,
          type: "success",
        });
      });
    },
    handleRepayment(scope) {
      console.log(scope.row);
      this.repayForm = Object.assign({}, defaultRepayForm);
      this.repayForm.bill = scope.row.id;
      this.repayForm.money = scope.row.money - scope.row.repayment;
      this.dlgRepayVisible = true;
      this.$nextTick(() => {
        this.$refs.repayFormRef.clearValidate();
      });
    },
    HandleSaveRepay() {
      this.$refs.repayFormRef.validate(async (valid) => {
        if (!valid) return;

        this.repayForm.user = this.uid;
        const res = await addRepaymentBill(this.repayForm);

        const { id } = res;
        if (id > 0) {
          this.getLendList();
        }
        this.dlgRepayVisible = false;
      });
    },
    handleDeleteRepay(datas, scope) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const $index = scope.$index;
          const res = await delRepaymentBill(scope.row.id);
          datas.splice($index, 1);
          let sum = datas.reduce((prev, cur) => prev + cur["money"], 0);
          console.log("sum=", sum);
          this.curr_row["repayment"] = sum;
          this.curr_row["balance"] = this.curr_row["money"] - sum;
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("取消删除!");
        });
    },
    expandChange(row, expandedRows) {
      console.log(row, expandedRows);
      if (expandedRows.length > 0) {
        this.curr_row = row;
      } else {
        this.curr_row = null;
      }
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-table {
    margin-top: 10px;
    width: 100%;
  }

  .item {
    margin-top: 8px;
  }
}
</style>